package com.example.mylibrary.tcp;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import static android.content.ContentValues.TAG;
import static com.example.mylibrary.tcp.PackageHeadInfo.g_FPHead;
import static com.example.mylibrary.tcp.PackageHeadInfo.g_FPTail;
import static com.example.mylibrary.tcp.TCPConst.HEAD_LEN;


/**
 * Created by Administrator on 2018/1/4.
 */

public class SocketClient {

    private Socket SOCKET = null;
    private Socket socketTcp;
    private boolean b;

    private byte[] buf;

    private int UseLen;

    public SocketClient() {
        buf = new byte[1024 * 1024 * 4];
        UseLen = 0;
    }


    //private SocketClient(){}

    //private static SocketClient socketClients;

    //private static Socket socketTcp=null;


//    public static SocketClient socketClient() {
//
//            synchronized (SocketClient.class) {//加锁 多个进程使用
//                if(socketClients==null){//优化
//                    socketClients=new SocketClient();
//                }
//
//        }
//        return socketClients;
//    }

    /**
     * 获取TCP连接
     *
     * @param sIp  服务ip地址
     * @param prot 端口号
     * @param data 发送的数据
     * @param call CallBackSocketTCP 接口
     */
    public void getTCPConnect(String sIp, int prot, String data, final CallBackSocketTCP call) {
        try {
            socketTcp = new Socket(sIp, prot);
            Log.e(TAG, sIp + prot);
//			final SocketUtil socketUtil = new SocketUtil(socketTcp);
            sendData(data);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    b = true;
                    while (b) {
                        boolean ba = isConnect();
                        //把值传给接口，这里接口作用就是传值


                        call.isConnect(ba);
                        Log.e("isConnect是否连接-->", "" + ba);
                        String info = null;
                        try {
                            info = receiveData();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        call.Receive(info);
//						Log.e(TAG, info);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();


        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


//	public SocketUtil(Socket socket) {
//		super();
//		this.socket = socket;
//
//	}

    //断开连接
    public void closeConnect() {
        try {
            socketTcp.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //检测是否连接 如果断开就重连
    public boolean isConnect() {
        if (socketTcp.isClosed()) {//检测是否关闭状态
            //TODO 这个地方检测数 是断开，在这写重连的方法。

            return false;
        }
        return true;

    }

    //发送数据
    public void sendData(String data) throws IOException {
        //PrintWriter out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"GB2312"),true);
        OutputStream outputStream = socketTcp.getOutputStream();
        //String   strGBK =  new String(data.getBytes("UTF-8"),"GBK");
        outputStream.write(data.getBytes("GB2312"));
    }

    StringBuffer text = new StringBuffer();

    //接收数据
    public String receiveData() throws IOException {
        InputStream inputStream = socketTcp.getInputStream();
        byte[] buf = new byte[1024 * 1024 * 4];
        int len = inputStream.read(buf);
        String text = new String(buf, 0, len);
        return text;
    }

    //接收数据
    public String receiveData2() throws IOException {
        InputStream inputStream = socketTcp.getInputStream();
        byte[] buffer = new byte[1024];

        int len = inputStream.read(buffer);
        Log.e("buffer--->: ", buffer + "");
        Log.e("len--->: ", len + "");
        //UseLen=buf.length;
        System.arraycopy(buffer, 0, buf, UseLen, len);

        while (buf.length > HEAD_LEN) {

            byte[] bytHead = new byte[HEAD_LEN];

            System.arraycopy(buf, 0, bytHead, 0, HEAD_LEN);

            String strRes = new String(bytHead);


            Log.i(TAG, "strRes: "+strRes);
            int headleath = g_FPHead.length();
            String headStr = strRes.substring(0, headleath+2);
            Log.i("headStr",headStr);
            int packetlen = Integer.parseInt(strRes.substring(headleath+3, headleath + 12));
            Log.i("packetlen",packetlen+"");
            int commond = Integer.parseInt(strRes.substring(headleath + 12, headleath + 18));
            Log.i("commond",commond+"");
            int keylen = Integer.parseInt(strRes.substring(headleath + 18, headleath + 28));
            Log.i("keylen",keylen+"");
            int packtype = Integer.parseInt(strRes.substring(headleath + 28, headleath + 29));
            Log.i("packtype",packtype+"");
            int is = Integer.parseInt(strRes.substring(headleath + 29, headleath + 30));
            Log.i("is",is+"");
            String time = strRes.substring(headleath + 28, headleath + 38);

            if (headStr.equals(g_FPHead)) {

                //1.通过 strRes 去解析包长度，报类型。。。。
                if (packetlen < UseLen - HEAD_LEN) {
                    //
                } else {
                    byte[] bytpacket = new byte[packetlen];
                    System.arraycopy(buf, HEAD_LEN, bytpacket, 0, packetlen - HEAD_LEN);
                    String packetStr = new String(bytpacket);
                    Log.i("packetStr", packetStr);
                    int endlen = g_FPTail.length();
                    String endStr = packetStr.substring(packetStr.length() - endlen, packetStr.length());
                    if (endStr.equals(g_FPTail)) {
                        String result = packetStr.substring(0, packetStr.length() - endlen);
                        System.arraycopy(buf, packetlen, buf, 0, UseLen-packetStr.length());
                        UseLen=UseLen-packetStr.length();

                        return result;

                    }
                }
                //strRes =
                //2.根据包长度从buf再取出数据长度的数据
                //3.判断包尾是否正确；


                //4.解析出数据包体转成String，进行包体解析


                byte[] bytPacketData = new byte[HEAD_LEN];

//				char sBufferLen = new char[GTP_OFFSET_COMMANDID + 1];
//				memset(sBufferLen, 0, GTP_OFFSET_COMMANDID + 1);
//				int iHeadLen = strlen(g_FPHead);
//				memcpy(sBufferLen, m_sData + iHeadLen, GTP_OFFSET_COMMANDID);
//				int iPackageLen = atoi(sBufferLen);
//				delete[] sBufferLen;
//
//				if (iPackageLen < GTP_OFFSET_HEAD_LEN || iPackageLen > m_CurLen) {
//					Unlock();
//					return;
//				}
//
//				if (iPackageLen > MAX_CLIENT_BUFFER_SIZE) {
//					m_CurLen = 0;
//					Unlock();
//					return;
//				}
//
//				memcpy(pMsg, m_sData, iPackageLen);
//
//				if (!PackageTailIsNormal(pMsg, iPackageLen)) {
//					m_CurLen = 0;
//					Unlock();
//					return;
//				}
            }

        }


        String str = new String(buf, 0, len);
        Log.i("str-->", str);
//        while (len!=0){
//            String str = new String(buf, 0, len);
//            text.append(str);
//            Log.i("text-->",text.toString());
//        }
        return str;
    }


    public interface CallBackSocketTCP {
        //这个回调用于获取服务端返回的数据
        void Receive(String info);

        //判断是否处在连接在状态
        void isConnect(boolean state);
    }

    public void closeSocket() {
        if (socketTcp != null) {
            try {
                b = false;
                socketTcp.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {

        }
    }
}

